package controller

import (
	"blog/dao"
	"encoding/json"
	"github.com/julienschmidt/httprouter"
	"net/http"
	"strconv"
	"time"
)

/**
 * @api            		{POST} /admin/posts/list 文章列表
 * @apiName        		admin posts list
 * @apiGroup       		admin/posts
 * @apiVersion     		1.0.0
 * @apiDescription 		文章列表
 * @apiPermission  		admin
 * @apiSampleRequest 	/admin/posts/list
 * @apiParam {number} 	page         页号
 * @apiParam {string} 	type         分类ID
 */
func AdminPostsListHandle(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {

	dao.CommonAction(r, w)

	guest := new(dao.GuestSession)
	//检查是否未登录
	if guest.Init(r).CheckIsLogin() == false {
		dao.SendResult(w, dao.ERR_NO_LOGIN.Code, dao.ERR_NO_LOGIN.Message, nil)
		return
	}

	//页号
	pageId, err := strconv.ParseInt(r.URL.Query().Get("page"), 10, 64)
	if err != nil {
		pageId = 1
	}
	if pageId < 1 {
		pageId = 1
	}
	//每一页数据条数
	PageSize, _ := strconv.ParseInt(r.URL.Query().Get("pageSize"), 10, 64)
	if PageSize == 0 {
		PageSize = int64(20)
	}

	//关键字
	keyWord := func() string {
		param1 := ps.ByName("keyWord")
		if param1 != "" {
			return param1
		}
		param2 := r.URL.Query().Get("keyWord")
		return param2
	}()
	//分类
	typeId := func() int64 {
		param1, _ := strconv.ParseInt(ps.ByName("type"), 10, 64)
		if param1 != 0 {
			return param1
		}
		param2, _ := strconv.ParseInt(r.URL.Query().Get("type"), 10, 64)
		return param2
	}()
	//标签
	tagName := func() string {
		param1 := ps.ByName("tagName")
		if param1 != "" {
			return param1
		}
		param2 := r.URL.Query().Get("tagName")
		return param2
	}()

	lists := dao.GetPostListByKeyWord(keyWord, tagName, typeId, pageId, PageSize, true)
	dao.SendResult(w, dao.ERR_NONE.Code, dao.ERR_NONE.Message, lists)

}

/**
 * @api            		{POST} /admin/posts/add 文章添加
 * @apiName        		admin posts add
 * @apiGroup       		admin/posts
 * @apiVersion     		1.0.0
 * @apiDescription 		文章添加
 * @apiPermission  		admin
 * @apiSampleRequest 	/admin/posts/add
 * @apiParam {number} 	post_type     分类id
 * @apiParam {string} 	title         标题
 * @apiParam {string} 	content       内容
 * @apiParam {number} 	is_private    是否私有 1是 0否
 * @apiParam {number} 	is_show       是否显示 1是 0否
 * @apiParam {number} 	is_remark     是否允许评论 1是 0否
 * @apiParam {number} 	is_temp       是否草稿 1是 0否
 * @apiParam {number} 	is_star       是否标星 1是 0否
 * @apiParam {number} 	add_time      添加时间(可选,2018-09-04 16:29:34)
 */
func AdminPostsAddHandle(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	dao.CommonAction(r, w)

	guest := new(dao.GuestSession)
	//检查是否未登录
	if guest.Init(r).CheckIsLogin() == false {
		dao.SendResult(w, dao.ERR_NO_LOGIN.Code, dao.ERR_NO_LOGIN.Message, nil)
		return
	}

	post := dao.PostDataReal{}
	post.Author = int(guest.Uid)

	postType, _ := strconv.ParseInt(r.PostFormValue("post_type"), 10, 64)
	is_postType_ok := dao.CheckAddPostTypeId(postType)
	if is_postType_ok == false {
		dao.SendResult(w, dao.ERR_POSTTYPE_ERROR.Code, dao.ERR_POSTTYPE_ERROR.Message, nil)
		return
	}
	post.PostType = int(postType)

	title := dao.TrimHtml(r.PostFormValue("title"))
	is_title_ok, errMsg := dao.CheckPostTitle(title)
	if is_title_ok == false {
		dao.SendResult(w, dao.ERR_POST_TITLE_ERROR.Code, errMsg, nil)
		return
	}
	post.Title = title

	content := r.PostFormValue("content")
	is_content_ok, errMsg := dao.CheckPostContent(content)
	if is_content_ok == false {
		dao.SendResult(w, dao.ERR_POST_CONTENT_ERROR.Code, errMsg, nil)
		return
	}
	post.Content = content

	if r.PostFormValue("is_private") == "1" {
		post.IsPrivate = 1
	} else {
		post.IsPrivate = 0
	}

	if r.PostFormValue("is_show") == "0" {
		post.IsShow = 0
	} else {
		post.IsShow = 1
	}

	if r.PostFormValue("is_remark") == "0" {
		post.IsRemark = 0
	} else {
		post.IsRemark = 1
	}

	if r.PostFormValue("is_temp") == "1" {
		post.IsTemp = 1
	} else {
		post.IsTemp = 0
	}

	if r.PostFormValue("is_star") == "1" {
		post.IsStar = 1
	} else {
		post.IsStar = 0
	}

	param_addTime := r.PostFormValue("add_time")
	if param_addTime != "" {
		T, err := time.Parse(dao.TimeLayout, param_addTime)
		if err != nil {
			post.AddTime = time.Now().Format(dao.TimeLayout)
		}
		post.AddTime = T.Format(dao.TimeLayout)
	} else {
		post.AddTime = time.Now().Format(dao.TimeLayout)
	}
	post.LastEditTime = post.AddTime

	err := post.Add()
	if err != nil {
		dao.SendResult(w, dao.ERR_POST_SAVE_ERROR.Code, dao.ERR_POST_SAVE_ERROR.Message, nil)
	} else {
		dao.SendResult(w, dao.ERR_NONE.Code, dao.ERR_NONE.Message, post.Id)
		go func(D dao.PostDataReal) {
			T, _ := time.Parse(dao.TimeLayout, post.AddTime)
			post.AddTime = T.Format(time.RFC3339)
			post.LastEditTime = T.Format(time.RFC3339)
			dataStr, _ := json.Marshal(post)
			dao.EsIndexSaveData(dao.EsConf["INDEX_NAME_POST"], dao.EsConf["INDEX_NAME_POST"], string(dataStr), D.Id)
		}(post)
	}

	return
}

/**
 * @api            		{POST} /admin/posts/update 文章编辑
 * @apiName        		admin posts update
 * @apiGroup       		admin/posts
 * @apiVersion     		1.0.0
 * @apiDescription 		文章编辑
 * @apiPermission  		admin
 * @apiSampleRequest 	/admin/posts/update
 * @apiParam {number} 	post_type     分类id
 * @apiParam {string} 	title         标题
 * @apiParam {string} 	content       内容
 * @apiParam {number} 	is_private    是否私有 1是 0否
 * @apiParam {number} 	is_show       是否显示 1是 0否
 * @apiParam {number} 	is_remark     是否允许评论 1是 0否
 * @apiParam {number} 	is_temp       是否草稿 1是 0否
 * @apiParam {number} 	is_star       是否标星 1是 0否
 */
func AdminPostsUpdateHandle(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	dao.CommonAction(r, w)

	guest := new(dao.GuestSession)
	//检查是否未登录
	if guest.Init(r).CheckIsLogin() == false {
		dao.SendResult(w, dao.ERR_NO_LOGIN.Code, dao.ERR_NO_LOGIN.Message, nil)
		return
	}

	post := dao.PostDataReal{}
	id, err := strconv.ParseInt(r.PostFormValue("id"), 10, 64)
	if err != nil || id == 0 {
		dao.SendResult(w, dao.ERR_POST_ID.Code, dao.ERR_POST_ID.Message, nil)
		return
	}
	post.Id = int(id)
	err = post.Info()
	if err != nil {
		dao.SendResult(w, dao.ERR_POST_NOT_FIND.Code, dao.ERR_POST_NOT_FIND.Message, nil)
		return
	}

	postType, _ := strconv.ParseInt(r.PostFormValue("post_type"), 10, 64)
	is_postType_ok := dao.CheckAddPostTypeId(postType)
	if is_postType_ok == false {
		dao.SendResult(w, dao.ERR_POSTTYPE_ERROR.Code, dao.ERR_POSTTYPE_ERROR.Message, nil)
		return
	}
	post.PostType = int(postType)

	title := dao.TrimHtml(r.PostFormValue("title"))
	is_title_ok, errMsg := dao.CheckPostTitle(title)
	if is_title_ok == false {
		dao.SendResult(w, dao.ERR_POST_TITLE_ERROR.Code, errMsg, nil)
		return
	}
	post.Title = title

	content := r.PostFormValue("content")
	is_content_ok, errMsg := dao.CheckPostContent(content)
	if is_content_ok == false {
		dao.SendResult(w, dao.ERR_POST_CONTENT_ERROR.Code, errMsg, nil)
		return
	}
	post.Content = content

	if r.PostFormValue("is_private") == "1" {
		post.IsPrivate = 1
	} else {
		post.IsPrivate = 0
	}

	if r.PostFormValue("is_show") == "0" {
		post.IsShow = 0
	} else {
		post.IsShow = 1
	}

	if r.PostFormValue("is_remark") == "0" {
		post.IsRemark = 0
	} else {
		post.IsRemark = 1
	}

	if r.PostFormValue("is_temp") == "1" {
		post.IsTemp = 1
	} else {
		post.IsTemp = 0
	}

	if r.PostFormValue("is_star") == "1" {
		post.IsStar = 1
	} else {
		post.IsStar = 0
	}

	post.LastEditTime = time.Now().Format(dao.TimeLayout)

	err = post.Update()
	if err != nil {
		dao.SendResult(w, dao.ERR_POST_SAVE_ERROR.Code, dao.ERR_POST_SAVE_ERROR.Message, nil)
	} else {
		dao.SendResult(w, dao.ERR_NONE.Code, dao.ERR_NONE.Message, post.Id)
		go func(D dao.PostDataReal) {
			TA, _ := time.Parse(dao.TimeLayout, post.AddTime)
			TE, _ := time.Parse(dao.TimeLayout, post.LastEditTime)
			post.AddTime = TA.Format(time.RFC3339)
			post.LastEditTime = TE.Format(time.RFC3339)
			dataStr, _ := json.Marshal(post)
			dao.EsIndexSaveData(dao.EsConf["INDEX_NAME_POST"], dao.EsConf["INDEX_NAME_POST"], string(dataStr), D.Id)
		}(post)
	}

	return
}
